<?php


namespace app\admin\controller\mall;


use app\admin\traits\Curd;
use app\common\business\Member;
use app\common\business\OrderGoods;
use app\common\business\Wechat;
use app\common\controller\AdminController;
use app\common\lib\ArrClass;
use app\common\lib\Str;
use app\common\model\MallGroupsGoods;
use app\common\model\MallGroupsOrder;
use app\common\model\MallGroupsOrderRefund;
use think\App;
use think\Model;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;

/**
 * Class Groupsorder
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="拼团订单管理")
 */
class Groupsorder extends AdminController
{

    protected $relationSearch = true;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallGroupsOrder();
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames2();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id){
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            switch($post['orderToStatus']){
                case 1: //确认付款
                    $post['status'] =1;
                    $post['paytime'] =time();
                    break;
                case 2: //核销
                    $post['isverify'] =1;
                    $post['status'] =2;
                    $post['verifytime'] =time();
                    break;
                case 4: //退款
                    break;
                default:
                    break;
            }
            $this->model->startTrans();
            try {
                $save = $row->save($post);

                if($save && $post['orderToStatus']==1){
                    // 更新订单表以及支付记录表
                    (new MemberPaylog())->where("order_id='".$id."'")->save(array('status'=>1,'paytime'=>time()));
                }
                if($post['orderToStatus'] ==2){
                    $orderinfo= $this->model->where("id='$id'")->find();
                    // 核销返利
                    if(!empty($orderinfo['parent_openid'])){
                        (new Member())->saveAccoutLog($orderinfo['parent_openid'],$orderinfo['first_price'],3, '分享返利');
                    }
                    // 核销返回用户钱包
                    if(!empty($orderinfo['openid'])){
                        (new Member())->saveAccoutLog($orderinfo['openid'],$orderinfo['payprice'],4, '平台返现');
                    }
                }

                if($save && $post['orderToStatus']==4 && $post['paytype']==1){
                    // 退款流程
                    $orderinfo =$this->model->find($id);
                    $refundno =Str::RandomStr();
                    $objClass = ArrClass::payAttr();
                    $obj = ArrClass::initClass('wx', $objClass, [], true);

                    $payprice =intval($orderinfo['payprice']*100);
                    $refundprice =intval($orderinfo['payprice']*100);
                    // 商城支付记录
                    $paylog = (new \app\common\business\MemberPaylog())->getByOrderTypeId($orderinfo['id'],4);
                    if(!$paylog){
                        $this->model->rollback();
                        $this->error('退款失败');
                    }
                    $result= $obj->refund($paylog['ordersn'],$refundno,$payprice,$refundprice,['refund_desc'=>'同城生活商城支付退款']);
                    if($result['return_code'] == 'SUCCESS'){
                        if($result['result_code'] =='SUCCESS'){

                            $orderinfo->save(array('status'=>4,'isrefund'=>1,'refundtime'=>time()));
                        }else{
                            $this->model->rollback();
                            $this->error('退款失败');
                        }
                    }else{
                        $this->model->rollback();
                        $this->error('退款失败');
                    }
                }
            } catch (\Exception $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            $this->model->commit();
            $this->success('保存成功');
        }
        switch ($row['status']){
            case 0:
                $row['statusname'] ='待付款';
                break;
            case 1:
                if($row['isverify'] ==1){
                    $row['statusname'] ='已核销';
                }else{
                    $row['statusname'] ='待核销';
                }
                break;
            case 2:
                $row['statusname'] ='已完成';
                break;
            case 3:
                $row['statusname'] ='售后中';
                break;
            case 4:
                $row['statusname'] ='已退款';
                break;
            default:
                $row['statusname'] ='已取消';
                break;
        }
        $userinfo =(new Wechat())->getOpenidById($row['openid']);
        $row['nickName'] =$userinfo['nickName'];

        $this->assign('row', $row);

        return $this->fetch();
    }
}